package com.bigknow.appstore.proxy.handler.statistics;

import com.bigknow.appstore.proxy.cache.ICacheManager;
import com.bigknow.appstore.proxy.entity.ProxyLog;
import com.bigknow.appstore.proxy.handler.base.BaseOutboundHandler;
import com.bigknow.appstore.proxy.log.ILogWriter;
import com.bigknow.appstore.proxy.server.IProxyServer;
import com.bigknow.appstore.proxy.util.HandlerVariables;
import com.bigknow.appstore.proxy.vo.RequestVo;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http.FullHttpMessage;

/**
 * 访问成功后统计数据
 * Created by chaos on 2016/9/26.
 */
@ChannelHandler.Sharable
public class SucceedStatisticsHandler extends BaseOutboundHandler {

    public SucceedStatisticsHandler(IProxyServer proxyServer, ICacheManager cacheManager, ILogWriter writer) {
        super(proxyServer, cacheManager, writer);
    }

    @Override
    public void write(ChannelHandlerContext ctx, FullHttpMessage msg, ChannelPromise promise) {

        long size = 0;
        try {
            size = Long.parseLong(msg.headers().get("Content-Length"));
        } catch (Exception e) {
            logger.error("Content-Length is :  " + msg.headers().get("Content-Length"));
        }
        writer.writeLog(writer.createSuccessLogObject(
                HandlerVariables.requestVoForCurrentResponse.get(ctx.channel().id().asLongText()), size));
        ctx.write(msg, promise);
    }

}
